package com.CMS.client.datasource;

import java.util.List;

import com.CMS.client.PrivilegeService;
import com.CMS.client.PrivilegeServiceAsync;
import com.CMS.server.domain.Privilege;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.data.fields.DataSourceTextField;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class PrivilegeDataSource extends BaseDataSource{
	
	private SelectItem typeSelect;
	private SelectItem pathSelect;
	
	public PrivilegeDataSource(){
		// CREO EL COMBO DE TIPOS DE PRIVILEGIOS
		typeSelect = new SelectItem(); 
		typeSelect.setOptionDataSource(new PrivilegeTypeDataSource());
		typeSelect.setValueField(getId());
		typeSelect.setAccessKey(getId());
		typeSelect.setDisplayField(getDescription());
		typeSelect.setEmptyPickListMessage(message.messageNoRecords());
	    DataSourceTextField fieldType = new DataSourceTextField("type","Tipo");
	    fieldType.setEditorType(typeSelect);        
        // CREO COMBO CON LAS VISTAS
        //createViews();
        pathSelect = new SelectItem();
        pathSelect.setOptionDataSource(new PrivilegeViewDataSource());
        pathSelect.setValueField(getId());
        pathSelect.setDisplayField(getDescription());
        pathSelect.setEmptyPickListMessage(message.messageNoRecords());
        DataSourceTextField fieldView = new DataSourceTextField("path","Vista");
        fieldView.setEditorType(pathSelect);
        
        addField(fieldType);
        addField(fieldView);
        
        GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() {
  		  @Override 
  		  public void onUncaughtException(Throwable e) {
  		    GWT.log(e.getMessage(), e); 
  		  }
  		});
	}	
	
	private void copyValues(Privilege from, Record to) {
		to.setAttribute(getType(), from.getType().getDescription());
		to.setAttribute(getPath(), from.getPath().getDescription());
		to.setAttribute(getDescription(), from.getDescription());
		to.setAttribute(getId(), from.getId());
		to.setAttribute(getAddDate(), from.getAddDate());
		to.setAttribute(getModDate(), from.getModDate());
		to.setAttribute(getFlagDelete(), from.getFlagDelete());
	}

	public static String getType(){
		return "type";
	}
	
	public static String getPath(){
		return "path";
	}


	@Override
	protected void executeFetch(final String requestId, final DSRequest request,
			final DSResponse response) {
		PrivilegeServiceAsync rpc = GWT.create(PrivilegeService.class);
		rpc.fetch(new AsyncCallback<List<Privilege>>() {
			
			@Override
			public void onSuccess(List<Privilege> result) {
				final int startIndex = (request.getStartRow() < 0) ? 0 : request.getStartRow();
				final int endIndex = (request.getEndRow ()== null)? -1 : request.getEndRow();
				int size = result.size ();
                if (endIndex >= 0) {
                	if (endIndex < startIndex) {
                		size = 0;
                    }
                    else {
                        size = endIndex - startIndex + 1;
                    }
                }
                //Creamos los registros a devolver
				Record[] regs = new Record[result.size()];
				if (size > 0) {
					for (int i = 0; i < regs.length; i++) {
						Record record = new Record();
						copyValues(result.get(i), record);
						regs[i] = record;
					}
				}
				response.setData(regs);
				//IMPORTANTE: para que funcione el paginado debemos especificar
				//el total de registro del result set
				response.setTotalRows (result.size ());
				processResponse(requestId, response);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}
		});
	}


	@Override
	protected void executeAdd(final String requestId, DSRequest request,
			final DSResponse response) {
		
		PrivilegeServiceAsync rpc = GWT.create(PrivilegeService.class);
		final ListGridRecord rec = new ListGridRecord (request.getData());
		rpc.create(rec.getAttribute(getDescription()), new Long(typeSelect.getValue().toString()), 
				new Long(pathSelect.getValue().toString()), 
				new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						response.setStatus(RPCResponse.STATUS_FAILURE);
						processResponse(requestId, response);
					}

					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub
						
					}
				});
		
	}


	@Override
	protected void executeUpdate(final String requestId, DSRequest request,
			final DSResponse response) {
		
		PrivilegeServiceAsync rpc = GWT.create(PrivilegeService.class);
		Record old = request.getOldValues();
		final ListGridRecord rec = new ListGridRecord (request.getData());
		
		rpc.update((rec.getAttribute(getDescription()) == null) ? old.getAttribute(getDescription()) : rec.getAttribute(getDescription()),
				   (rec.getAttributeAsBoolean(getFlagDelete()) == null) ? old.getAttributeAsBoolean(getFlagDelete()) : rec.getAttributeAsBoolean(getFlagDelete()), 
				   (rec.getAttributeAsLong(getId()) == null) ? old.getAttributeAsLong(getId()) : rec.getAttributeAsLong(getId()),
				   (typeSelect.getDisplayValue().toString()), 
				   (pathSelect.getDisplayValue().toString()), 
				   new AsyncCallback<Void>() {

					@Override
					public void onFailure(Throwable caught) {
						response.setStatus(RPCResponse.STATUS_FAILURE);
						processResponse(requestId, response);
					}

					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub						
					}
				});
	}


	@Override
	protected void executeRemove(final String requestId, DSRequest request,
			final DSResponse response) {

		PrivilegeServiceAsync rpc = GWT.create(PrivilegeService.class);
		final ListGridRecord rec = new ListGridRecord (request.getData());
		rpc.remove(rec.getAttributeAsLong(getId()), new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}

			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	/*private void createViews(){
		PrivilegeViewServiceAsync rpc = GWT.create(PrivilegeViewService.class);
		PrivilegeView privilegio = new PrivilegeView();
		privilegio.setDescription("PrivilegeView");
		rpc.create(privilegio, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Error");
			}

			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub
				
			}
		});
		privilegio = new PrivilegeView();
		privilegio.setDescription("RolView");
		rpc.create(privilegio, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Error");
			}

			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub
				
			}
		});
		PrivilegeType tipo = new PrivilegeType();
		tipo.setDescription("MODIFICAR");
		PrivilegeTypeServiceAsync serv = GWT.create(PrivilegeTypeService.class);
		serv.create(tipo, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub
				
			}
		});
	}*/
}
